package com.xsf.pay.common.constraints.validator;

import cn.hutool.core.util.StrUtil;
import com.xsf.pay.common.constraints.URL;
import com.xsf.pay.common.utils.ValidationUtils;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @Author xujianfeng
 * @DATE 2023/7/7 10:48
 */
public class UrlValidator implements ConstraintValidator<URL, String> {

    private boolean require;

    @Override
    public void initialize(URL constraintAnnotation) {
        require = constraintAnnotation.required();
        ConstraintValidator.super.initialize(constraintAnnotation);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isNotBlank(value)) {
            return ValidationUtils.isUrl(value);
        }
        return !require;
    }
}
